package com.ws.ssmzongjie3.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ws.ssmzongjie3.bean.ProVo;
import com.ws.ssmzongjie3.bean.User;
import com.ws.ssmzongjie3.service.Acl_RoleService;
import com.ws.ssmzongjie3.service.UserService;
import com.ws.ssmzongjie3.util.Res;
import com.ws.ssmzongjie3.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private Acl_RoleService acl_RoleService;
    @RequestMapping("/list")
    public String select(Model model, ProVo proVo, User user){
        System.out.println("links:"+user);

        PageHelper pageHelper = new PageHelper();//分页帮助类
        pageHelper.startPage(proVo.getCurrentPage(),proVo.getPageSize());//分页   每页条数
        List<User> qianUsers = userService.listUser(user);
        PageInfo pageInfo = new PageInfo(qianUsers);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("user",user);

        return "/WEB-INF/admin/user/list";
    }
//    @RequestMapping("/zhuxiao")
//    public String zhuxiao(HttpSession session,User user) {
//        session.removeAttribute("user");
//        userService.deleteUser(user);
//        return "redirect:/luyou/shouye";
//    }

    @RequestMapping("/delete")
    public String delete(User user) {
        // 获取用户信息
        User oldUser = userService.getUserById(user);
        // 删除用户
        userService.deleteUser(user);
        // 如果用户有头像，删除对应的图片文件
        if (oldUser != null && oldUser.getU_avatar() != null && !oldUser.getU_avatar().isEmpty()) {
            File avatarFile = new File(Res.fileDir + oldUser.getU_avatar());
            if (avatarFile.exists()) {
                avatarFile.delete();
            }
        }
        return "redirect:/user/list";
    }

    @RequestMapping("/mima")
    public String mima() {
        return "/WEB-INF/qiantai/user/xiugaimima";
    }

    @RequestMapping("/xiugaimima")
    public String xiugaimima(User user,String newPassword,HttpSession session) {
        User userById = userService.getUserById(user);
        boolean verify = false;
        if (userById != null){
            verify = SecurityUtils.verify(user.getU_pass(), userById.getU_pass());
        }
        if (verify){
            String encrypt = SecurityUtils.encrypt(newPassword);
            user.setU_pass(encrypt);
            userService.updateUser(user);
            User userById1 = userService.getUserById(user);
            session.setAttribute("user",userById1);
        }
        return "redirect:/user/gerenxinxi";
    }

    @RequestMapping("/xiugaixinxi")
    public String xiugaixinxi(HttpSession session,User user, MultipartFile image) throws IOException {
        // 获取旧用户信息
        User oldUser = userService.getUserById(user);
        // 如果上传了新图片
        if ((image.getSize() != 0)||!(image.getOriginalFilename().equals(""))){
            // 删除旧图片
            if (oldUser != null && oldUser.getU_avatar() != null && !oldUser.getU_avatar().isEmpty()) {
                File oldAvatarFile = new File(Res.fileDir + oldUser.getU_avatar());
                if (oldAvatarFile.exists()) {
                    oldAvatarFile.delete();
                }
            }
        
            // 保存新图片
            System.out.println("文本框名字"+image.getName());
            System.out.println("文件名字"+image.getOriginalFilename());
            System.out.println("文件大小"+image.getSize());
            System.out.println("文件格式"+image.getContentType());
        
            String uuid = UUID.randomUUID().toString().replace("-", "");
            System.out.println(uuid);
            String fileName = uuid+"."+image.getOriginalFilename().split("\\.")[1];
            System.out.println(fileName);
            image.transferTo(new File(Res.fileDir+fileName));
            user.setU_avatar(fileName);
        }
        String formattedDate = "";
        if (user.getU_birthday() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
             formattedDate = sdf.format(user.getU_birthday());
            System.out.println("格式化后的日期：" + formattedDate);
            user.setUser_birthday(formattedDate);
        }

        if (user.getU_pass()!=null){
            user.setU_pass(SecurityUtils.encrypt(user.getU_pass()));
        }


        userService.updateUser(user);
            User userById = userService.getUserById(user);
            session.setAttribute("user",userById);
            return "redirect:/user/gerenxinxi";
    }

    @RequestMapping("/update")
    public String xiugai(HttpSession session,User user, MultipartFile image) throws IOException {
        // 获取旧用户信息
        User oldUser = userService.getUserById(user);
        // 如果上传了新图片
        if ((image.getSize() != 0)||!(image.getOriginalFilename().equals(""))){
            // 删除旧图片
            if (oldUser != null && oldUser.getU_avatar() != null && !oldUser.getU_avatar().isEmpty()) {
                File oldAvatarFile = new File(Res.fileDir + oldUser.getU_avatar());
                if (oldAvatarFile.exists()) {
                    oldAvatarFile.delete();
                }
            }

            // 保存新图片
            System.out.println("文本框名字"+image.getName());
            System.out.println("文件名字"+image.getOriginalFilename());
            System.out.println("文件大小"+image.getSize());
            System.out.println("文件格式"+image.getContentType());

            String uuid = UUID.randomUUID().toString().replace("-", "");
            System.out.println(uuid);
            String fileName = uuid+"."+image.getOriginalFilename().split("\\.")[1];
            System.out.println(fileName);
            image.transferTo(new File(Res.fileDir+fileName));
            user.setU_avatar(fileName);
        }
        String formattedDate = "";
        if (user.getU_birthday() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            formattedDate = sdf.format(user.getU_birthday());
            System.out.println("格式化后的日期：" + formattedDate);
            user.setUser_birthday(formattedDate);
        }

        if (user.getU_pass()!=null){
            user.setU_pass(SecurityUtils.encrypt(user.getU_pass()));
        }


        userService.updateUser(user);
        return "redirect:/user/list";
    }

    @RequestMapping("/huixian")
    public String update(User user, Model model) {
        User userById = userService.getUserById(user);
        String formattedDate = "";
        if (userById.getU_birthday() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            formattedDate = sdf.format(userById.getU_birthday());
            System.out.println("格式化后的日期：" + formattedDate);
            userById.setUser_birthday(formattedDate);
        }
        userById.setUser_birthday(formattedDate);
        model.addAttribute("user",userById);
        return "/WEB-INF/admin/user/update";
    }

    @RequestMapping("/add")
    public String add(User user) {
        return "/WEB-INF/admin/user/add";
    }

    @RequestMapping("/gerenzhongxin")
    public String gerenzhongxin() {
        return "/WEB-INF/qiantai/user/gerenzhongxin";
    }

    @RequestMapping("/gerenxinxi")
    public String gerenxinxi() {
        return "/WEB-INF/qiantai/user/gerenxinxi";
    }
    @RequestMapping("/login")
    public String login(User user, HttpSession session){
        User userByName = userService.getUserByName(user);
        boolean verify = false;
        if (userByName != null){
             verify = SecurityUtils.verify(user.getU_pass(), userByName.getU_pass());
        }

        System.out.println(userByName+"==============");
        System.out.println(user);
        System.out.println(verify);
        if (verify){
            session.setAttribute("user",userByName);
            return "redirect:/luyou/shouye";
        }

        return "/login";
    }

    @RequestMapping("/insert")
    public String insert(User user, MultipartFile image) throws IOException {
        System.out.println(user);
        if ((image.getSize() != 0)||!(image.getOriginalFilename().equals(""))){
            System.out.println("文本框名字"+image.getName());
            System.out.println("文件名字"+image.getOriginalFilename());
            System.out.println("文件大小"+image.getSize());
            System.out.println("文件格式"+image.getContentType());

            String uuid = UUID.randomUUID().toString().replace("-", "");
            System.out.println(uuid);
            String fileName = uuid+"."+image.getOriginalFilename().split("\\.")[1];
            System.out.println(fileName);
            image.transferTo(new File(Res.fileDir+fileName));
            user.setU_avatar(fileName);
        }
        String encrypt = SecurityUtils.encrypt(user.getU_pass());
        user.setU_pass(encrypt);
        userService.insertUser(user);
        return "redirect:/user/list";
    }

    @RequestMapping("/zhuce")
    public String zhuce(User user, MultipartFile image) throws IOException {
        System.out.println(user);
        if ((image.getSize() != 0)||!(image.getOriginalFilename().equals(""))){
            System.out.println("文本框名字"+image.getName());
            System.out.println("文件名字"+image.getOriginalFilename());
            System.out.println("文件大小"+image.getSize());
            System.out.println("文件格式"+image.getContentType());

            String uuid = UUID.randomUUID().toString().replace("-", "");
            System.out.println(uuid);
            String fileName = uuid+"."+image.getOriginalFilename().split("\\.")[1];
            System.out.println(fileName);
            image.transferTo(new File(Res.fileDir+fileName));
            user.setU_avatar(fileName);
        }
        String encrypt = SecurityUtils.encrypt(user.getU_pass());
        user.setU_pass(encrypt);
        userService.insertUser(user);
        return "/login";
    }
    @RequestMapping("/tuichu")
    public String tuichu(HttpSession session){
        session.removeAttribute("user");
        return "/login";
    }


    @RequestMapping("/checkUsername")
    @ResponseBody
    public Map<String, Boolean> checkUsername(@RequestParam String username,@RequestParam Integer userId) {



        
        User user1 = new User();
        user1.setU_name(username);
        User userByName = userService.getUserByName(user1);
        Map<String, Boolean> response = new HashMap<>();
        User userById = null;
        if (userId != null){
            User user = new User();
            user.setUser_id(userId);
            userById = userService.getUserById(user);
            if (userById != null && userById.getU_name() != null) {
                if(userById.getU_name().equals(username)){
                    response.put("exists", false);
                }
            }
        }

        if (userByName != null && userByName.getU_name() != null) {
            response.put("exists", true);
        }
        return response;
    }

    @RequestMapping("/verifyPassword")
    @ResponseBody
    public Map<String, Object> verifyPassword(@RequestParam("oldPassword") String oldPassword, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User currentUser = (User) session.getAttribute("user");
        if (currentUser != null) {
            boolean valid = SecurityUtils.verify(oldPassword, currentUser.getU_pass());
            result.put("valid", valid);
        } else {
            result.put("valid", false);
        }
        return result;
    }
}
